package hu.fic.weddingstorefinder.db.table;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import hu.fic.weddingstorefinder.db.generatedtable.GeneratedPOI;
import hu.fic.weddingstorefinder.utils.Constants;

public class POI extends GeneratedPOI {
	private static final String LOG_TAG = "POI";
	
	public POI(SQLiteDatabase db, Activity activity) {
		super(db, activity);
	}
	
	public void processPoiListFromJSON(JSONArray poiList) throws Exception {
		if (poiList.length() == 0) {
			return;
		}
		
		try {
			db.beginTransaction();
			for (int i = 0; i < poiList.length(); i++) {
				JSONObject poiObj = poiList.optJSONObject(i);
				this.clear();
				//Log.i(LOG_TAG, poiObj.optString(Constants.JSON_NAME));
				this.setCustomPOIId(poiObj.optInt(Constants.JSON_ID));
				this.load();
				if (this.rowCount() > 0) {
					this.clear();
					//update poi with customid
					this.setCustomPOIId(poiObj.optInt(Constants.JSON_ID));
					this.addAddressUpdate(poiObj.optString(Constants.JSON_ADDRESS));
					this.addCityUpdate(poiObj.optString(Constants.JSON_CITY));
					this.addLatitudeUpdate(poiObj.optDouble(Constants.JSON_LATITUDE));
					this.addLongitudeUpdate(poiObj.optDouble(Constants.JSON_LONGITUDE));
					this.addPhoneUpdate(poiObj.optString(Constants.JSON_PHONE));
					this.addPOINameUpdate(poiObj.optString(Constants.JSON_NAME));
					this.addPOIStatusUpdate(poiObj.optInt(Constants.JSON_STATUS));
					this.addZIPCodeUpdate(poiObj.optString(Constants.JSON_ZIPCODE));
					this.update();
				} else {
					//add new poi:
					this.clear();
					this.setCustomPOIId(poiObj.optInt(Constants.JSON_ID));
					this.setAddress(poiObj.optString(Constants.JSON_ADDRESS));
					this.setCity(poiObj.optString(Constants.JSON_CITY));
					this.setLatitude(poiObj.optDouble(Constants.JSON_LATITUDE));
					this.setLongitude(poiObj.optDouble(Constants.JSON_LONGITUDE));
					this.setPhone(poiObj.optString(Constants.JSON_PHONE));
					this.setPOIName(poiObj.optString(Constants.JSON_NAME));
					this.setPOIStatus(poiObj.optInt(Constants.JSON_STATUS));
					this.setZIPCode(poiObj.optString(Constants.JSON_ZIPCODE));
					this.newRow();
				}
			}
			this.clear();
			//delete marked pois:
			this.setPOIStatus(Constants.POI_STATUS_TODELETE);
			this.load();
			POI deleteTable = new POI(db, activity);
			while (this.nextRow()) {
				deleteTable.setCustomPOIId(this.getCustomPOIId());
				deleteTable.delete();
				deleteTable.clear();
			}
			db.setTransactionSuccessful();
		} catch (Exception e) {
			throw e;
		} finally {
			db.endTransaction();
		}
		
	}
}